#ifndef TREEMODEL_H
#define TREEMODEL_H

#include <QtCore/QAbstractItemModel>
#include <QtCore/QVector>
#include "TreeNode.h"

class TreeModel : public QAbstractItemModel {
    Q_OBJECT

public:
    explicit TreeModel(QObject* parent = nullptr);
    ~TreeModel();

    // QAbstractItemModel interface
    QModelIndex index(int row, int column, const QModelIndex& parent) const override;
    QModelIndex parent(const QModelIndex& child) const override;
    int rowCount(const QModelIndex& parent) const override;
    int columnCount(const QModelIndex& parent) const override;
    QVariant data(const QModelIndex& index, int role) const override;
    bool setData(const QModelIndex& index, const QVariant& value, int role) override;
    Qt::ItemFlags flags(const QModelIndex& index) const override;


    // Custom methods
    void setTreeData(const QVector<TreeNode>& nodes);
    Q_INVOKABLE QVector<QString> getCheckedNodes() const;
    Q_INVOKABLE void setCheckedById(const QVector<QString>& ids, int checked);
    Q_INVOKABLE void expandAll();
    Q_INVOKABLE void filter(const QString& text);


signals:
    void expandTree(const QModelIndex& index);

private:
    TreeNode* getNode(const QModelIndex& index) const;
    bool filterAcceptsNode(TreeNode* node) const;
    void updateChildrenCheckedState(TreeNode* node, int checkstate);
    void updateParentCheckedState(TreeNode* node, int checkstate);
    int getAllChildCheckState(TreeNode* parent);
    void expandChildren(const QModelIndex& parent);
    void updateGroupNameHash(TreeNode* node, const QString& parentIdPath = "", const QString& parentNamePath = "");
    void updateAllNodes();
    void updateNode(const QModelIndex& index);

    TreeNode* m_rootNode;
    QHash<QString, TreeNode*> m_nodeMap;  // For quick lookup by id
    QHash<QString, QVector<QString>> m_GroupNameHash;  // 存储节点完整路径的哈希表
    QString m_FirstTreeId{""};
    QString m_filterText;
};
#endif // TREEMODEL_H
